// src/utils/appUpdates.ts
import { Alert, Linking, Platform } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import api from '../services/api';

interface AppUpdateInfo {
  latestVersion: string;
  minimumVersion: string;
  updateUrl: string;
  releaseNotes: string;
  forceUpdate: boolean;
}

export async function checkForUpdates() {
  try {
    const currentVersion = DeviceInfo.getVersion();

    const response = await api.post<AppUpdateInfo>('/app/version/check-update', {
        platform: Platform.OS,
        version: currentVersion,
      },
    );

    const updateInfo = response.data;

    if (shouldUpdate(currentVersion, updateInfo)) {
      showUpdateAlert(updateInfo);
    }
  } catch (error) {
    console.error('[Update] Check failed:', error);
  }
}

function shouldUpdate(currentVersion: string, updateInfo: AppUpdateInfo): boolean {
  return compareVersions(currentVersion, updateInfo.latestVersion) < 0;
}

function compareVersions(v1: string, v2: string): number {
  const parts1 = v1.split('.').map(Number);
  const parts2 = v2.split('.').map(Number);

  for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
    const part1 = parts1[i] || 0;
    const part2 = parts2[i] || 0;

    if (part1 < part2) return -1;
    if (part1 > part2) return 1;
  }

  return 0;
}

function showUpdateAlert(updateInfo: AppUpdateInfo) {
  const buttons = updateInfo.forceUpdate
    ? [
      {
        text: '立即更新',
        onPress: () => Linking.openURL(updateInfo.updateUrl),
      },
    ]
    : [
      {
        text: '稍后提醒',
        style: 'cancel' as const,
      },
      {
        text: '立即更新',
        onPress: () => Linking.openURL(updateInfo.updateUrl),
      },
    ];

  Alert.alert(
    '发现新版本',
    `版本 ${updateInfo.latestVersion} 已发布\n\n${updateInfo.releaseNotes}`,
    buttons,
    { cancelable: !updateInfo.forceUpdate }
  );
}